<?php

/* Login page
 */

// if clause required here for 'seamonkey browser'. Gives warning of: "session already open"
if ( ! session_id() ) {
	session_start();
}

// set login default type to "login" (normal) 
if( ! isset($_SESSION['set']) ) { 
	$_SESSION['ltype']="normal";
	$_SESSION['set']="set";
} 
// Save POSTED login type
if( isset($_POST['ltype']) ) { 
	$_SESSION['ltype']=$_POST['ltype'];
	$_POST['ltype']="";
} 
$error=""; // define var for later use

// check if 'POST' operation in progress
if( isset($_POST['name']) && isset($_POST['password']) ) {
	$name=htmlentities($_POST['name']);
	$pword=htmlentities($_POST['password']);
	// Clear POST vars
	$_POST['name']="";		// Clear var
	$_POST['password']="";	// Clear var
	
	// Validate data strings: name and password. $error set if invalid data
	if ( ! strlen($name)  ) {
		$error="<b>ERROR:</b> The Username field is empty.";
    } else if ( ! strlen($pword)  ) {
		$error="<b>ERROR:</b> The Password field is empty.";
	} else if ( strlen($name) < 3 ) {
		$error="<b>ERROR:</b> Username has too few characters (>2 and <25). ";
	} else if ( strlen($name) > 24 ) {
		$error="<b>ERROR:</b> Username has too many characters (>2 and <25). ";
	} else if ( strlen($pword) < 3 ) {
		$error="<b>ERROR:</b> Password has too few characters (>2 and <25). ";
	} else if ( strlen($pword) > 24 ) {
		$error="<b>ERROR:</b> Password has too many characters (>2 and <25). ";
	} else if ( ! ctype_alnum( $name .$pword ) ) {
		$error="<b>ERROR:</b> The Username and Password may only contain: letters and digits.";
	} 
	// Display page (with error if $error set)
	if ( "$error" ) {
		display($error);
		exit;
	}
	// Normal login
	if ( $_SESSION['ltype'] == "normal" ) {
		$userArray = file("registered_users.txt");
		if ( testUserDetails($name,$pword) == 0 ) { 
			$_SESSION['user']="$name";
			header( 'Location: index.php' );
			// Alterative method of redirecting
			//echo "<script type=\"text/javascript\" language=\"javascript\">";
			//echo "window.location = \"index.php\"";
			//echo "</script>";
			exit;
		} else {
			$error="<b>ERROR:</b>The entered Username and Password combination is not registered.";
			display($error);
			exit;
		}
	// Register login
	} else if ( $_SESSION['ltype'] == "new" ) {
		$userArray = file("registered_users.txt");
		if ( registerNew($name,$pword) != 0 ) {
			display($error);
			exit;
		}
		$_SESSION['user']="$name";
		$fh=fopen("favorites_$name.txt","a");	//Create new user favorites file
		fclose($fh);  							//close the file
//		echo "<h1>Hi there, got here</h1>";
//		exit;
		
		header( 'Location: index.php' );
		// Alterative method of redirecting
		//echo "<script type=\"text/javascript\" language=\"javascript\">";
		//echo "window.location = \"index.php\"";
		//echo "</script>";
		exit;
	} else { // should never ever get here.
		echo "<h1>Hi there something went wrong in the web server. Please start over.</h1>";
		exit;
	} 
}
display($error);
exit;

// Test for user:pw match 0=match 1=no match
function testUserDetails($nam,$pw) {
	global $userArray;
	//$userArray = file("registered_users.txt");
	$test=trim($nam .":" .$pw);
	foreach($userArray as $up) {
		if ( strcmp(trim($up),$test) == 0 ) { return 0; }
	}
	return 1;
}

// Check that user name is not already registered, then save user data
function registerNew($nam,$pw) {
	global $userArray;
	
	if ( testUserDetails($nam,$pw) == 0 ) {
		global $error;
		$error="Information: Usename: " .$nam ." is already registered.";
		return 1;
	}

	//$userArray = file("registered_users.txt");
	$test2="ok";
	$test=trim($nam .":");
	foreach($userArray as $up) {
		$up=trim($up);
		if (strlen($up) && strpos($up,$test) === 0 ) { unset($test2); } // HUGE PROBLEM HERE $test2 unset everytime ?????? 3Hrs
	}
	if ( isset($test2) ) { 						 // if username not already in use
		$fh=fopen("registered_users.txt","a");   // open registered_users.txt file for append 
		fwrite($fh,trim($nam .":" .$pw) ."\n");  // write user data to file, one line
		fclose($fh);					 		 // close the file
		return 0;
	} else { 									// user name is in use
		global $error;
		$error="Information: Usename: " .$nam ." is already registered.";
		return 1;
	}                            
}

// provide html heade
function giveHeader() {

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
?>

<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<!--
    * File Name:  login.php
    * Author: Arthur Brown SID: 6335497
    * Date Written: 20/10/2009 12:00
    * Version: 1.0
    * Last Modified: 
    * Description: PHP Assignment
-->

<head>
<title>Login</title>
</head>
<body>

<?php

} // end of giveHeader function

// Display page
function display($e) {
	giveHeader();
	echo "<h1>Welcome to Arthur's Site. You are Not Logged in.<br />";
	if ( $_SESSION['ltype'] == "normal" ) {
		echo "<h1>Please Log In</h1>";
	} else {
		echo "<h1>Please enter a Username and Password to register to Arthur's site.</h1>";
	} ?>

<br />
<form name="login_form" method="post" action="login.php">
<table border="1">
<tr>
  <th> Username </th>
  <td> <input type="text" name="name"> </td>
</tr>
<tr>
  <th> Password </th>
  <td> <input type="password" name="password"> </td>
</tr>
<tr>
  <td colspan="2" align="center">
	<input type="hidden" name="type" value="normal" >

	<?php // do login type dependant button label
	if ( $_SESSION['ltype'] == "normal" ) {
		echo "<input type=\"submit\" value=\"Log In\">";
	} else {
		echo "<input type=\"submit\" value=\"Register to Arthur's site\">";
	} ?>

  </td>
</tr>
</table>
</form>

	<?php // do login type dependant button
	if ( $_SESSION['ltype'] == "normal" ) {
		echo "<br /><br /><br />";
		echo "<form name=\"new_form\" method=\"post\" action=\"login.php\">";
		echo "<input type=\"hidden\" name=\"ltype\" value=\"new\" >";
		echo "<input type=\"submit\" value=\"Register to Arthur's site\">";
		echo "</form>";
	} else {
		echo "Note: Username and Password:<br />Minimum 3 and Maximum 23 characters.";
		echo "<br /><br /><br />";
		echo "<form name=\"new_form\" method=\"post\" action=\"login.php\">";
		echo "<input type=\"hidden\" name=\"ltype\" value=\"normal\" >";
		echo "<input type=\"submit\" value=\"Log in\">";
		echo "</form>";
	}
	// Display error if available
	if ( "$e" ) {
		echo "<br /><br />";
		echo $e;
	}
?>
</body>
</html>
<?php
} // end of display function
